package com.hmh.student.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmh.student.system.entity.SysMenu;
import com.hmh.student.system.service.ISysMenuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 菜单管理 前端控制器
 * </p>
 *
 * @author xyf
 * @since 2025-04-09
 */
@RestController
@RequestMapping("/sysMenu")
@Api(tags = "菜单管理接口")
public class SysMenuController {

    @Autowired
    private ISysMenuService sysMenuService;

    /**
     * 新增菜单
     */
    @PostMapping("/add")
    @ApiOperation("新增菜单")
    public Map<String, Object> addMenu(@RequestBody SysMenu sysMenu) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = sysMenuService.save(sysMenu);
            if (success) {
                result.put("success", true);
                result.put("msg", "菜单添加成功");
                result.put("data", sysMenu);
            } else {
                result.put("success", false);
                result.put("msg", "菜单添加失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "菜单添加异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 修改菜单信息
     */
    @PutMapping("/update")
    @ApiOperation("修改菜单信息")
    public Map<String, Object> updateMenu(@RequestBody SysMenu sysMenu) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = sysMenuService.updateById(sysMenu);
            if (success) {
                result.put("success", true);
                result.put("msg", "菜单更新成功");
            } else {
                result.put("success", false);
                result.put("msg", "菜单更新失败，菜单ID可能不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "菜单更新异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/delete")
    @ApiOperation("删除菜单")
    public Map<String, Object> deleteMenu(@RequestParam Integer menuId) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = sysMenuService.removeById(menuId);
            if (success) {
                result.put("success", true);
                result.put("msg", "菜单删除成功");
            } else {
                result.put("success", false);
                result.put("msg", "菜单删除失败，菜单ID可能不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "菜单删除异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取菜单详情
     */
    @GetMapping("/getById")
    @ApiOperation("获取菜单详情")
    public Map<String, Object> getMenuById(@RequestParam Integer menuId) {
        Map<String, Object> result = new HashMap<>();
        try {
            SysMenu sysMenu = sysMenuService.getById(menuId);
            if (sysMenu != null) {
                result.put("success", true);
                result.put("msg", "查询成功");
                result.put("data", sysMenu);
            } else {
                result.put("success", false);
                result.put("msg", "菜单不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "查询异常: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询菜单
     */
    @GetMapping("/page")
    @ApiOperation("分页查询菜单")
    public Page<SysMenu> pageMenu(
            @RequestParam(required = false) String menuName,
            @RequestParam(required = false) Integer parentId,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(defaultValue = "1") Integer current) {
        return sysMenuService.queryMenuPage(menuName, parentId, pageSize, current);
    }




    @GetMapping("/getAllMenu")
    public Map<String, List<SysMenu>> getAllMenu(){

        List<SysMenu> sysMenuList = sysMenuService.list();

        Map<String, List<SysMenu>> result = new HashMap<>();

        for (SysMenu sysMenu : sysMenuList) {
            String parentId = String.valueOf(sysMenu.getParentId());

            if (!result.containsKey(parentId)) {
                result.put(parentId, new ArrayList<>());
            }

            result.get(parentId).add(sysMenu);
        }
        return result;
    }

    /**
     * 获取层级菜单列表（用于下拉选择）
     */
    @GetMapping("/getHierarchicalMenus")
    public List<Map<String, Object>> getHierarchicalMenus() {
        // 获取所有菜单并按父ID分组
        Map<String, List<SysMenu>> menuMap = getAllMenu();
        // 构建层级菜单列表
        return buildHierarchicalMenuList(menuMap, "0", 0);
    }

    // 构建层级菜单列表
    private List<Map<String, Object>> buildHierarchicalMenuList(Map<String, List<SysMenu>> menuMap, String parentId, int level) {
        List<Map<String, Object>> result = new ArrayList<>();
        List<SysMenu> menus = menuMap.get(parentId);
        if (menus != null) {
            for (SysMenu menu : menus) {
                Map<String, Object> item = new HashMap<>();
                item.put("menuId", menu.getMenuId());
                item.put("menuName", getLevelPrefix(level) + menu.getMenuName());
                result.add(item);
                // 递归添加子菜单
                result.addAll(buildHierarchicalMenuList(menuMap, String.valueOf(menu.getMenuId()), level + 1));
            }
        }
        return result;
    }

    // 生成层级前缀
    private String getLevelPrefix(int level) {
        if (level == 0) return "";
        return "　".repeat(level * 2) + "├─ ";
    }
}